import {login, logout, getInfo, getCurrent} from "../../api/user";
import {getToken, setToken, removeToken} from '../../utils/auth'
import store from "../index";
import {getCart} from "../../api/cart";
import {Toast} from "vant";

const user = {
    state: {
        token: getToken(),
        name: '',
        avatar: '',
        user: {},
        cartCount: ''
    },

    mutations: {
        SET_TOKEN(state, token){
            state.token = token;
        },
        SET_NAME(state, name){
            state.name = name;
        },
        SET_AVATAR(state, avatar){
            state.avatar = avatar;
        },
        SET_USER(state, user){
            state.user = user;
        },
        SET_CARTCOUNT(state, cartCount){
            state.cartCount = cartCount;
        }
    },

    actions: {
        //会员登录
        Login({commit}, data){
            return new Promise((resolve, reject) => {
                login(data.username, data.password).then(res => {
                    const token = res.data;
                    setToken(token);
                    commit('SET_TOKEN', token);
                    resolve();
                }).catch(err => {
                    reject(err)
                })
            })
        },
        //获取用户信息
        GetInfo({commit, state}){
            return new Promise((resolve, reject) => {
                getCurrent().then(res => {
                    commit('SET_USER', res.data)
                    commit('SET_NAME', res.data.username);
                    resolve(res);
                }).catch(err => {
                    reject(err);
                })
                getCart().then(res => {
                    commit('SET_CARTCOUNT', res.data.length)
                })
            })
        },
        //退出登录
        LoGout({commit, state}){
            return new Promise((resolve, reject) => {
                logout(store.getters.token).then((res) => {
                    commit('SET_TOKEN', '')
                    commit('SET_USER', {})
                    commit('SET_NAME', '')
                    commit('SET_CARTCOUNT', '')
                    removeToken()
                    resolve()
                }).catch(err => {
                    reject(err);
                }).finally(() => {
                    Toast.success('登出成功')
                })
            })
        },

        // 前端 登出
        FedLogOut({commit}) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }




    }
}

export default user;
